package sample

import javafx.application.Application
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.layout.BorderPane
import javafx.stage.Stage
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import sample.Utils.DownMap
import sample.bean.Point

import javafx.stage.DirectoryChooser
import java.lang.Exception
import javafx.scene.control.Alert.AlertType

import javafx.scene.control.Alert
import sample.bean.MapTypeBean
import javafx.scene.control.cell.PropertyValueFactory
import kt.Utils.getRegionColRow
import kt.Utils.getRegionColRowForest
import kt.Utils.getRegionColRowTianDi


class Main : Application() {
    override fun start(primaryStage: Stage) {

        val selectList = FXCollections.observableArrayList(levels)
        val chekBox = ChoiceBox(FXCollections.observableArrayList(selectList)).apply {
            value = selectList[10]
        }
        val selectTypeList = FXCollections.observableArrayList(mapTypes)
        val checkTypeBox = ChoiceBox(FXCollections.observableArrayList(selectTypeList))
            .apply { value = selectTypeList[0] }
        var selectMapType = 0

        val tableTypeList = FXCollections.observableArrayList<MapTypeBean>(mapTypeSelect)
        val typeTableView = TableView<MapTypeBean>(tableTypeList)
        typeTableView.setPrefSize(395.0, 210.0)

        val firstColumn = TableColumn<MapTypeBean, CheckBox>("选择")
        firstColumn.cellValueFactory = PropertyValueFactory("check")

        val secondColumn = TableColumn<MapTypeBean, String>("地图类型")
        secondColumn.cellValueFactory = PropertyValueFactory("name")

        val thirdColumn = TableColumn<MapTypeBean, String>("地图url ID")
        thirdColumn.cellValueFactory = PropertyValueFactory("type")

        typeTableView.columns.addAll(firstColumn, secondColumn, thirdColumn)


        val textFieldLeftX = TextField(listRange2[0].x.toString())
        val textFieldLeftY = TextField(listRange2[0].y.toString())
        val textFieldRightX = TextField(listRange2[1].x.toString())
        val textFieldRightY = TextField(listRange2[1].y.toString())
        var downPath = ""


        val lablePath = Label("文件存储路径:未设置")
        val labelProgress = Label("下载进度:")

        val root = BorderPane().apply {
            padding = Insets(40.0)
            center = VBox(20.0).apply {
                alignment = Pos.CENTER

                children.add(HBox(30.0).apply {
                    alignment = Pos.CENTER_LEFT
                    children.addAll(Label("地图类型"), checkTypeBox.apply {
                        selectionModel.selectedIndexProperty().addListener { observable, oldValue, newValue ->
                            selectMapType = newValue.toInt()
                            if (selectMapType == 0) {
                                typeTableView.isVisible = true
                                typeTableView.isManaged = true
                            } else {
                                typeTableView.isVisible = false
                                typeTableView.isManaged = false
                            }
                        }
                    })
                })

                children.add(HBox().apply {
                    alignment = Pos.CENTER
                    children.addAll(typeTableView)
                })

                children.add(HBox().apply {
                    children.addAll(Label("请输入下载范围:"))
                })
                children.add(HBox(10.0).apply {
                    alignment = Pos.CENTER
                    children.addAll(Label("左上角: x="), textFieldLeftX, Label("y="), textFieldLeftY)
                })

                children.add(HBox(10.0).apply {
                    alignment = Pos.CENTER
                    children.addAll(Label("右下角: x="), textFieldRightX, Label("y="), textFieldRightY)
                })

                children.add(HBox(20.0).apply {
                    alignment = Pos.CENTER_LEFT
                    children.addAll(Label("请选择下载级数"), chekBox)
                })

                children.add(HBox(20.0).apply {
                    alignment = Pos.CENTER_LEFT
                    children.addAll(Label("请选择存储路径"), Button("选择").apply {
                        setOnAction {
                            val directoryChooser = DirectoryChooser()
                            val file = directoryChooser.showDialog(primaryStage)
                            val path = file.path //选择的文件夹路径

                            path?.let {
                                lablePath.text = "文件存储路径:${it}"
                                downPath = it
                            }
                        }
                    }, lablePath)
                })

                children.add(labelProgress.apply {
                    isVisible = false
                    isManaged = false
                })

                children.add(HBox(50.0).apply {
                    alignment = Pos.CENTER_RIGHT
                    children.addAll(Button("开始下载").apply {
                        setOnAction {
                            if (downMap.isStartDown) {
                                val alert = Alert(AlertType.INFORMATION)
                                alert.titleProperty().set("提示")
                                alert.headerTextProperty().set("已经开始下载")
                                alert.showAndWait()
                                return@setOnAction
                            }

                            labelProgress.isVisible = true
                            labelProgress.isManaged = true
                            labelProgress.text = "正在测试链接"
                            downMap.testUrlConnect {
                                if (it) {
                                    Platform.runLater {
                                        openDownMap(
                                            textFieldLeftX,
                                            textFieldLeftY,
                                            textFieldRightX,
                                            textFieldRightY,
                                            chekBox,
                                            downPath,
                                            labelProgress,
                                            tableTypeList,
                                            selectMapType
                                        )
                                    }
                                } else {
                                    Platform.runLater {
                                        labelProgress.text = "请检查网络是否通畅"
                                        val alert = Alert(AlertType.ERROR)
                                        alert.titleProperty().set("错误")
                                        alert.headerTextProperty().set("下载链接连接失败，请检查网络是否通畅")
                                        alert.showAndWait()
                                    }
                                }
                            }
                        }
                    })
                })
            }
        }

        primaryStage.title = "地图切片下载"
        primaryStage.scene = Scene(root)
        primaryStage.sizeToScene()
        primaryStage.show()

        primaryStage.setOnCloseRequest {
            downMap.mScope?.cancel()
            downMap.isInterrupt = true
        }
    }

    private fun openDownMap(
        textFieldLeftX: TextField,
        textFieldLeftY: TextField,
        textFieldRightX: TextField,
        textFieldRightY: TextField,
        chekBox: ChoiceBox<String>,
        downPath: String,
        labelProgress: Label,
        selectTypeList: ObservableList<MapTypeBean>,
        selectMapType: Int
    ) {
        val ranges = mutableListOf<Point>()
        try {
            ranges.apply {
                add(Point(textFieldLeftX.text.toDouble(), textFieldLeftY.text.toDouble()))
                add(Point(textFieldRightX.text.toDouble(), textFieldRightY.text.toDouble()))
            }
        } catch (e: Exception) {
            val alert = Alert(AlertType.ERROR)
            alert.titleProperty().set("错误")
            alert.headerTextProperty().set("请输入正确的下载范围")
            alert.showAndWait()
            return
        }

        val level = chekBox.value.toInt()
        if (downPath.isEmpty()) {
            val alert = Alert(AlertType.ERROR)
            alert.titleProperty().set("错误")
            alert.headerTextProperty().set("请选择下载路径")
            alert.showAndWait()
            return
        }

        downMap.mRootFileDir = downPath
        stratDown(labelProgress, ranges, level, selectMapType, selectTypeList)
    }

    private fun stratDown(
        labelProgress: Label,
        ranges: MutableList<Point>,
        level: Int,
        selectMapType: Int,
        selectTypeList: ObservableList<MapTypeBean>
    ) {
        GlobalScope.launch {
            labelProgress.isVisible = true
            labelProgress.isManaged = true
            if (selectMapType == 0) {
                val selectList = selectTypeList.filter {
                    it.check.isSelected
                }
                if (selectList.isEmpty()) {
                    Platform.runLater {
                        val alert = Alert(AlertType.ERROR)
                        alert.titleProperty().set("错误")
                        alert.headerTextProperty().set("请选择下载影像")
                        alert.showAndWait()
                    }
                    return@launch
                }

                val xjSelectMap = selectList.filter {
                    !it.name.contains("林地")
                }
                val ldSelectMap = selectList.filter {
                    it.name.contains("林地")
                }

                //新疆地图下载
                xjSelectMap.forEach {
                    downMap.startDown(ranges, level, it.type, it.name) { downNum, allCount ->
                        Platform.runLater {
                            if (downNum == allCount) {
                                labelProgress.text = "下载完成"
                            } else {
                                labelProgress.text = "${it.name}下载进度:${downNum}/${allCount}"
                            }
                        }
                    }
                }

                //林地小班下载
                ldSelectMap.forEach {
                    downMap.startDownLinDi(ranges, level, it.type, it.name) { downNum, allCount ->
                        Platform.runLater {
                            if (downNum == allCount) {
                                labelProgress.text = "下载完成"
                            } else {
                                labelProgress.text = "${it.name}下载进度:${downNum}/${allCount}"
                            }
                        }
                    }
                }
            } else {
                downMap.startDownTianDi(ranges, level) { downNum, allCount ->
                    Platform.runLater {
                        if (downNum == allCount) {
                            labelProgress.text = "下载完成"
                        } else {
                            labelProgress.text = "${"天地图"}下载进度:${downNum}/${allCount}"
                        }
                    }
                }
            }
        }
    }

}

private val downMap: DownMap by lazy { DownMap() }
private val listRange = arrayListOf<Point>(
    Point(73.44871179391436, 6.323497741027893),
    Point(134.77365151840308, 53.56204292863828)
)

private val listRange2 = arrayListOf<Point>(
    Point(73.44871179481356, 34.33619838854486),
    Point(96.38741218832189, 49.18135406263991)
)
private val levels = arrayListOf<String>(
    "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"
)

private val mapTypes = arrayListOf<String>(
    "林业前置机",
    "天地图"
)

private val mapTypeSelect: ArrayList<MapTypeBean> by lazy {
    arrayListOf<MapTypeBean>(
        MapTypeBean(CheckBox().apply { isSelected = true }, "新疆2019年影像", "84256fab-fafa-4fd4-bcb5-d319a3f2e4b6"),
        MapTypeBean(CheckBox(), "新疆2018年影像", "ddc33c25-d9c3-4c67-a10c-5d2ac72f6df6"),
        MapTypeBean(CheckBox(), "新疆2017年影像", "141f98c7-0bd0-4832-a1fc-d4cea75321aa"),
        MapTypeBean(CheckBox(), "新疆2016年影像", "7c4e7dee-801d-4832-a326-60addecdfca4"),
        MapTypeBean(CheckBox(), "新疆2013年影像", "3255cd55-586b-4905-9f91-8aca6b678464"),
        MapTypeBean(CheckBox(), "林地小班2019", "241a0c08-0174-4645-abca-23a04fad7254"),
        MapTypeBean(CheckBox(), "林地小班2018", "d3ffc167-ed4d-4baf-a73a-bdbe52990b3d"),
//        MapTypeBean(CheckBox(), "林地小班2017", "3255cd55-586b-4905-9f91-8aca6b678464"),
//        MapTypeBean(CheckBox(), "林地小班2010", "3255cd55-586b-4905-9f91-8aca6b678464"),
    )
}

fun main(args: Array<String>) {
    Application.launch(Main::class.java, *args)
    //downMap.startDown(listRange, 9)
    //println(getRegionColRowTianDi(listRange2, 17))
}
